import queue
import sqlite3
import threading
import time
from datetime import datetime
# from osgeo import ogr, osr


# def conversionTimes(datatime):
#     datetime_obj = datetime.strptime(datatime, "%d%m%y%H%M%S.%f")
#     conversionTime = int(time.mktime(datetime_obj.timetuple()) * 1000.0 + datetime_obj.microsecond / 1000.0)
#     return conversionTime


# def recalculate(points, distance):
#     source = osr.SpatialReference()
#     source.ImportFromEPSG(4326)
#
#     target = osr.SpatialReference()
#     # target.ImportFromEPSG(32650)
#     target.ImportFromProj4("+proj=aea +ellps=krass +lon_0=105 +lat_1=25 +lat_2=47")
#
#     transform = osr.CoordinateTransformation(source, target)
#     geoline = ogr.Geometry(ogr.wkbLineString)
#
#     for part in points:
#         point_str = ("POINT (%s %s)" % (part[1], part[0]))
#         point = ogr.CreateGeometryFromWkt(point_str)
#         point.Transform(transform)
#         geoline.AddPoint(point.GetX(), point.GetY())
#     if geoline.IsEmpty() is False and len(geoline.GetPoints()) > 1:
#         length = geoline.Length()
#         o_area = length * distance / 666.666
#         poly = geoline.Buffer(distance / 2)
#         buffer_area = (poly.Area() - (3.1415926 * (distance / 2) * (distance / 2))) / 666.666
#
#         # if buffer_area < 0.3:
#         #    buffer_area = 0.0
#
#         # print("Length: %s  O_Area: %s  Buffer_Area: %s" % (length, o_area, buffer_area))
#         return True, buffer_area, length, o_area
#     else:
#         return False, 0, 0, 0.0
from utils import converseTime


class Operation(object):
    def __init__(self, configs):
        self.conn = None
        self.configs = configs

    def operate(self):
        pass

    def setDB(self, conn):
        db_path = "/Users/fez/Downloads/"
        db_name = "865242053033447.db"
        db = db_path + db_name
        self.conn = sqlite3.connect(db, timeout=50)


class CoordinateOperation(Operation):
    def operate(self):
        with self.conn:
            try:
                c = self.conn.cursor()
                # print(self.configs)
                self.configs['uploadtime'] = converseTime.conversionDataBaseTime(str(self.configs['uploadtime']))
                self.configs['uploadtime'] = int(self.configs['uploadtime'])
                c.execute(
                    "INSERT INTO DeviceIoTCoordinate (Longitude,Latitude,UploaddateTime,LinkedOperatingId) VALUES ("
                    "%f,%f,%d,'%s')" % (
                        self.configs['latitude'], self.configs['lontitude'], self.configs['uploadtime'], self.configs['linkedOperatingId']))
                c.close()
            except Exception as ex:
                print("exceptionCoordinateOperation%s" % ex)


class WorkInsertOperation(Operation):
    def operate(self):
        with self.conn:
            try:
                c = self.conn.cursor()
                print(self.configs)
                # startTime = conversionTimes(self.configs['WorkingStartTime'])
                # stopTime = conversionTimes(self.configs['WorkingStopTime'])
                # uploadTime = conversionTimes(self.configs['UploadDateTime'])
                # c.execute(
                #     "INSERT INTO DeviceIoTWorking (WorkingStartTime,WorkingStopTime,WorkingWatetCounting,"
                #     "WorkingWaterUsage, "
                #     "WorkingLocation,WorkingArea,WorkingDistance,UploadDateTime,LinkedOperatingId,Id) "
                #     "VALUES (%d,%d,%d,%f,'%s',%f,%f,%d,'%s','%s')" %
                #     (startTime, stopTime, self.configs['WorkingWatetCounting'],
                #      self.configs['WorkingWaterUsage'], self.configs['WorkingLocation'], self.configs['WorkingArea'],
                #      self.configs['WorkingDistance'], uploadTime, self.configs['LinkedOperatingId'],
                #      self.configs['Id']))
            except Exception as ex:
                print("exceptionWorkUpdateOperation%s" % ex)

    pass

class WorkSelectOperation(Operation):
    def operate(self):
        with self.conn:
            try:
                c = self.conn.cursor()
                print(self.configs)
                c.execute("select * from DeviceIoTWorking WHERE Id = '%s'" % self.configs['Id'])
                results = c.fetchall()
                for var in results:
                    st = var[0]
                    et = var[7]
                    id = var[9]
                    c.execute(
                        "select Longitude,Latitude from DeviceIoTCoordinate where UploadDateTime >= %d and "
                        "UploadDateTime<=%d ORDER BY UploadDateTime" % (st, et))
                    coordresults = c.fetchall()
            except Exception as ex:
                print("exceptionWorkUpdateOperation%s" % ex)

class WorkUpdateOperation(Operation):
    def operate(self):
        with self.conn:
            try:
                c = self.conn.cursor()
                print(self.configs)
            except Exception as ex:
                print("exceptionBufferMergeOperation%s" % ex)


class IotDBManger(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self, name="IotDBManger")
        self.opqueue = queue.Queue()  # operation

    def add_operation(self, operation):
        self.opqueue.put(operation)

    def run(self):
        while True:
            if self.opqueue.qsize() > 0:
                option = self.opqueue.get()
                option.setDB(self)
                option.operate()

# if __name__ == '__main__':
# IotDBManger = IotDBManger()
